﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.SignalR;
using STT.Business;
using STT.Entities;
using System.Threading.Tasks;
using System.Web;

namespace STT.Admin
{
    public class ChatHub : Hub
    {
        public static List<UserDetail> ConnectedUsers = new List<UserDetail>();
        //static DataTable  tb = BTbDangNhap.SelectAllChat();
        public void Connect(string TenDN, string userName, string image)
        {
            var idConnect = Context.ConnectionId;

            ConnectedUsers.Add(new UserDetail { ConnectionId = idConnect, UserName = userName.TrimEnd(), TenDN = TenDN.TrimEnd(), Image = image.TrimEnd() });                           
            
            #region
            //tenDN = tenDN.Trim();

            //Clients.Caller.thongBao("Identity: " + tb.Rows.Count);

            //for (int i = 0; i < tb.Rows.Count; i++)
            //{
                //if (ConnectedUsers.Count(x => x.TenDN == tb.Rows[i]["TenDN"].ToString().TrimEnd()) == 0)
                //{
                //    ConnectedUsers.Add(new UserDetail
                //     {
                //         ConnectionId = "",
                //         UserName = tb.Rows[i]["TenHV"].ToString().TrimEnd(),
                //         TenDN = tb.Rows[i]["TenDN"].ToString().TrimEnd(),
                //         Image = tb.Rows[i]["Anh"].ToString() == "" ? "avatar-default.jpg" : tb.Rows[i]["Anh"].ToString().TrimEnd()
                //     });
                //    //Clients.Caller.thongBao(tb.Rows[i]["Anh"].ToString()== "" ? "avatar-default.jpg" : tb.Rows[i]["Anh"].ToString().TrimEnd());
                //}
            //}
            //Clients.Caller.thongBao("So user sau do: " + ConnectedUsers.Count);

            //if (ConnectedUsers.Count(x => x.TenDN == tenDN) > 0)
            //{
            //    // Neu chua co trong danh sach chat thi them vào
            //    var user = ConnectedUsers.FirstOrDefault(x => x.TenDN == tenDN);
            //    user.ConnectionId = idConnect;
#endregion

                // Goi ham hien thi danh sach chat cho user vua dang nhap
                Clients.Caller.onConnected(ConnectedUsers);

                // goi ham hien thi thong bao online cho cac user khac
                Clients.AllExcept(idConnect).onNewUserConnected(idConnect, TenDN /*, userName, image*/);

               // Clients.Caller.thongBao("Connected");
            //}
            //else
            //    
        }
        public void LoadMessage(string IdGui, string IdNhan, string idConnect, bool isScroll, string lastTime)
        {
            if(IdGui.Contains("HV"))
                Clients.Caller.messageReceived(BTbChat.SelectMessageForHocVien(IdGui, IdNhan, lastTime).GetXml(), idConnect, IdNhan, isScroll);
            else if (IdGui.Contains("GV"))
                Clients.Caller.messageReceived(BTbChat.SelectMessageForManager(IdGui, IdNhan, lastTime).GetXml(), idConnect, IdNhan, isScroll);
        }

        public void SendMessage(string toUserId, string TenDN, string message, bool isPublic, bool isEndcode)
        {
            TenDN = TenDN.TrimEnd();

            string fromUserId = Context.ConnectionId;

            //var toUser = ConnectedUsers.FirstOrDefault(x => x.TenDN == TenDN);
            var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);

            var thoiGianGui = DateTime.Now;
            
            message = isEndcode == true ? HttpUtility.HtmlEncode(message) : message;

            BTbChat.Insert(new ETbChat
            {
                IdGui = fromUser.TenDN,
                IdNhan = toUserId == "HV-1" ? "HV-1" : TenDN,
                NoiDung = message, // Có mã hóa chuỗi hay ko
                ThoiGianGui = thoiGianGui,
                TrangThai = toUserId == "" ? false : true,
            });

            if (!isPublic && toUserId != "HV-1")
            {
                //if (toUser != null && fromUser != null)
                //{
                // Gui thong tin cho ben chat
                if (toUserId != "")
                    Clients.Client(toUserId).sendMessage(fromUserId, fromUser.TenDN, fromUser.Image, fromUser.UserName, message, thoiGianGui.ToString("HH:mm:ss"), true, isPublic);

                // Hien thi thong tin tai cua so chat cua minh
                // send to caller user
                Clients.Caller.sendMessage(toUserId, TenDN,fromUser.Image, fromUser.UserName, message, thoiGianGui.ToString("HH:mm:ss"), false, isPublic);
                //}
            }
            else
            {
                Clients.Client(fromUserId).messageReceivedAll(toUserId, fromUser.UserName, fromUser.Image, message, thoiGianGui.ToString("HH:mm:ss"), false, isPublic);
                Clients.AllExcept(fromUserId).messageReceivedAll(toUserId, fromUser.UserName, fromUser.Image, message, thoiGianGui.ToString("HH:mm:ss"), true, isPublic);
            }
        }
        public override System.Threading.Tasks.Task OnDisconnected()
        {
            var item = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
            if (item != null)
            {
                // Xoa user khoi danh sach
                ConnectedUsers.Remove(item);
                //item.ConnectionId = "";
                // Xoa user tren trinh duyet
                Clients.All.onUserDisconnected(item.TenDN);
            }

            return base.OnDisconnected();
        }

        public override Task OnReconnected()
        {
            Clients.Caller.reConnected();
            return base.OnReconnected();
        }
    }
}